﻿// --------------
// 作者:Vitity
// --------------

using NICWebApi.Extensions.RESTfulResult.Filter;
using NICWebApi.Extensions.RESTfulResult.Providers;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// RESTful结果扩展方法
/// </summary>
public static class RESTfulResultExtensions
{
    /// <summary>
    /// 添加规范化结果服务
    /// </summary>
    /// <param name="builder">IMvcBuilder实例，用于构建ASP.NET Core MVC应用</param>
    /// <returns>配置后的IMvcBuilder实例</returns>
    /// <exception cref="ArgumentNullException">当builder为null时抛出</exception>
    public static IMvcBuilder AddRESTfulResult(this IMvcBuilder builder)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        builder.Services.AddRESTfulResult();

        return builder; // 返回配置后的IMvcBuilder实例
    }

    /// <summary>
    /// 添加规范化结果服务
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddRESTfulResult(this IServiceCollection services)
    {
        // 使用内部方法配置服务
        services.ConfigureRESTfulResultServices();

        return services;
    }

    /// <summary>
    /// 配置RESTful结果相关服务
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    private static IServiceCollection ConfigureRESTfulResultServices(this IServiceCollection services)
    {
        // 添加控制器相关服务，并配置过滤器
        services.AddControllers(options =>
        {
            // 添加结果过滤器
            options.Filters.Add<ResultFilter>();
            // 添加模型验证过滤器
            options.Filters.Add<ValidateModelFilter>();
            // 添加异常处理过滤器
            options.Filters.Add<ExceptionFilter>();
        });

        // 配置API行为选项，禁用默认的400响应
        services.Configure<ApiBehaviorOptions>(options =>
        {
            options.SuppressModelStateInvalidFilter = true; // 禁用默认 400 响应
        });

        // 添加规范化提供器
        services.TryAddSingleton<IUnifyResultProvider, RESTfulResultProvider>();

        // 添加Swagger配置
        services.AddRESTfulSwaggerGen();

        return services;
    }

    /// <summary>
    /// 单独添加Swagger配置，与RESTful结果分离
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddRESTfulSwaggerGen(this IServiceCollection services)
    {
        // 添加Swagger生成器服务，并配置Swagger文档
        services.AddSwaggerGen(c =>
        {
            // 添加操作过滤器，用于自定义Swagger响应
            c.OperationFilter<SwaggerOperationFilter>();
            // 添加模式过滤器，用于自定义Swagger模式
            c.SchemaFilter<SwaggerSchemaFilter>();
            // 添加枚举过滤器
            c.SchemaFilter<EnumSchemaFilter>();
        });

        return services;
    }
}